package com.fastloan.mgt.manager.app;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fastloan.mgt.customer.model.*;
import com.fastloan.mgt.customer.model.vo.CustomerExt;
import com.fastloan.mgt.customer.service.ZyCustomerService;
import com.fastloan.mgt.product.basics.model.vo.ProductHotExt;
import com.fastloan.mgt.product.basics.service.ProductService;
import com.fastloan.safe.core.util.ManagerKit;
import com.fastloan.safe.mgt.sys.model.CmuSysFile;
import com.fastloan.safe.mgt.sys.service.CmSysFileService;
import com.fastloan.safe.mgt.user.model.CmuUser;
import com.fastloan.utils.ObjUtil;
import com.kawins.base.baseabs.BaseController;
import com.kawins.result.ResultEnum;
import com.kawins.result.ResultTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by gelon on 2017/11/14.
 */
@RestController
@RequestMapping("/api/zy/wxapp/manager")
public class AppManagerController extends BaseController<CmuUser> {

    @Autowired
    ProductService productService;

    @Autowired
    ZyCustomerService customerService;

    @Autowired
    CmSysFileService fileService;


    /**
     * 获取机构下所有产品
     *
     * @param maxAmount    筛选条件
     * @param minAmount    筛选条件
     * @param monthlyOrder 升序降序排列
     */
    @PostMapping("/allProduct")
    public ResultTo allProduct(BigDecimal maxAmount, BigDecimal minAmount, Integer monthlyOrder) {
        String orgId = ManagerKit.getOrgId();
        if (monthlyOrder == null) {
            monthlyOrder = 0;
        }
        String order = monthlyOrder == 0 ? "ASC" : "DESC";
        Map<String, Object> map = new HashMap<>();
        map.put("orgId", orgId);
        map.put("maxAmount", maxAmount);
        map.put("minAmount", minAmount);
        map.put("order", order);
        map.put("date", new Date());
        List<ProductHotExt> productHotExts = productService.queryByOrg(map);
        productHotExts.forEach(this::putUrl);
        return new ResultTo().setData(productHotExts);
    }


    private static final int MINE = 0; // 我的
    private static final int STOCK = 2; //存量
    private static final int NOT_STOCK = 3; //非存量

    /**
     * 获取客户信息
     *
     * @param filter 根据条件筛选 @see #MINE
     */
    @PostMapping("/allCustomer")
    public ResultTo allCustomer(Integer filter, String customerName) {
        Map<String, Object> map = new HashMap<>();
        if (filter == null) {
            map.put("orgId", ManagerKit.getOrgId());
        } else {
            switch (filter) {
                case MINE:
                    map.put("userId", ManagerKit.getUserId());
                    break;
                case NOT_STOCK:
                    map.put("customerStatus", 0);
                    break;
                case STOCK:
                    map.put("customerStatus", 1);
                    break;
                default:
                    map.put("orgId", ManagerKit.getOrgId());
                    break;
            }
        }
        if (customerName != null) {
            map.put("customerName", customerName);
        }
        return dataPage(customerService, CustomerExt.class, "queryCustomerExt", map);
    }


    /**
     * 将产品对象的文件id 转化为文件url
     */
    private void putUrl(ProductHotExt productHotExt) {
        if (productHotExt.getImgId() != null) {
            CmuSysFile sysFile = fileService.selectByPrimaryKey(productHotExt.getImgId());
            if (sysFile != null) {
                productHotExt.setImgUrl(sysFile.getFileServer() + sysFile.getGroupName() + "/" + sysFile.getRemoteFileName());
            }
        }
        if (productHotExt.getLogoId() != null) {
            CmuSysFile sfile = fileService.selectByPrimaryKey(productHotExt.getLogoId());
            if (sfile != null) {
                productHotExt.setLogoUrl(sfile.getFileServer() + sfile.getGroupName() + "/" + sfile.getRemoteFileName());
            }
        }
    }

    /**
     * 新增一个营销客户
     */
    @PostMapping("/addCustomer")
    public ResultTo addCustomer(ZyCustomerStore zyCustomerStore, ZyCustomer zyCustomer, MultipartFile file) {
        zyCustomer.setPhoneNum(zyCustomerStore.getOwnerPhoneNum());
        if (zyCustomer.getPhoneNum() == null) {
            return new ResultTo(ResultEnum.OPERATION_FAILED);
        }
        customerService.addByStore(zyCustomerStore, zyCustomer, file);
        return new ResultTo();
    }


    /**
     * 获取单个营销客户的营销维护信息
     */
    @GetMapping("/customerMarketingInfo/{customerId}")
    public ResultTo getCustomerMarketingInfo(@PathVariable("customerId") String customerId) {
        Map<String, Object> map = customerService.getCustomerInfo(customerId);
        if (map != null) {
            return new ResultTo().setData(map);
        }
        return new ResultTo(ResultEnum.PARAM_ERROR);
    }


    /**
     * 更新一次营销信息
     *
     * @param customerJson           客户json
     * @param customerBusinessJson   客户商业信息
     * @param customerFinancingJson  客户融资信息
     * @param customerLoanDemandJson 客户贷款需求信息
     * @param customerMarketionJson  客户营销信息
     * @param customerMyBankJson     客户与我行信息
     * @param customerOtherBankJson  客户与他行信息
     * @param customerStoreJson      客户店铺信息
     * @param file                   店铺招牌
     */
    @PostMapping("/customerMarketion/save")
    public ResultTo saveCustomerMarketion(String customerJson, String customerBusinessJson, String customerFinancingJson,
                                          String customerLoanDemandJson,
                                          String customerMarketionJson, String customerMyBankJson, String customerOtherBankJson, String customerStoreJson, MultipartFile file) {
        ZyCustomer customer = JSONObject.parseObject(customerJson, ZyCustomer.class);
        ZyCustomerBusiness customerBusiness = JSONObject.parseObject(customerBusinessJson, ZyCustomerBusiness.class);
        List<ZyCustomerFinancing> customerFinancings = JSONArray.parseArray(customerFinancingJson, ZyCustomerFinancing.class);
        if (customerFinancings != null && customerFinancings.size() > 0) {
            customerFinancings = customerFinancings.stream()
                    .filter(zyCustomerFinancing -> !ObjUtil.isEmpty(zyCustomerFinancing.getFinancingExperience()))
                    .collect(Collectors.toList());
        }
        ZyCustomerLoanDemand customerLoanDemand = JSONObject.parseObject(customerLoanDemandJson, ZyCustomerLoanDemand.class);
        ZyCustomerMarketion customerMarketion = JSONObject.parseObject(customerMarketionJson, ZyCustomerMarketion.class);
        ZyCustomerMyBank customerMyBank = JSONObject.parseObject(customerMyBankJson, ZyCustomerMyBank.class);
        List<ZyCustomerOtherBank> customerOtherBanks = JSONArray.parseArray(customerOtherBankJson, ZyCustomerOtherBank.class);
        ZyCustomerStore customerStore = JSONObject.parseObject(customerStoreJson, ZyCustomerStore.class);
        customerService
                .updates(customer, customerBusiness, customerFinancings, customerLoanDemand, customerMarketion, customerMyBank, customerOtherBanks,
                        customerStore, file);
        return new ResultTo();
    }


}
